package com.example.demo.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.example.demo.util.JWTUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class JWTInterceptor  implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> modelMap = new HashMap<>();

        String id = null;
        System.out.println("这里是jwt");
        try{
            id = request.getParameter("auth_id");
            System.out.println("id:" + id);
        }catch(Exception e){
            System.out.println("无id");
            modelMap.put("errmessage","id无效!!");
            return false;
        }

        String token = null;

        Cookie[] cookies = request.getCookies();

        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("jwt-token")) {
                    token = cookie.getValue();
                    System.out.println("=====Cookie=====" + cookie.getValue().toString() + "=====Cookie=====");
                }
            }
        }

        try {
            Map<String , String> verifyResult = JWTUtil.verifyAndUpdate(token);//验证令牌
            if(!verifyResult.get("id").equals(id)){
                modelMap.put("errmessage","id未通过验证!");
                return false;
            }
            if (verifyResult.get("update").equals("true")){
                String cookieName = "jwt-token";
                String cookieVaule = verifyResult.get("token");
                Cookie jwtCookie = new Cookie(cookieName , cookieVaule);
                jwtCookie.setPath("/");
                response.addCookie(jwtCookie);
            }
            return true;//放行请求
        }catch (SignatureVerificationException e) {
            e.printStackTrace();
            modelMap.put("errmessage","无效签名!");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            modelMap.put("errmessage","token过期!");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            modelMap.put("errmessage","token算法不一致!");
        }
        catch (Exception e){
            e.printStackTrace();
            modelMap.put("errmessage","token无效!!");
        }
        //response.setStatus(401);
        modelMap.put("code","2222");//设置状态
        //将map 专为json  jackson
        String json = new ObjectMapper().writeValueAsString(modelMap);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
